'use strict';
module.exports = {
	/**
	 * 获取订单列表
	 * @url admin/system/user/sys/getChartsList2 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			type,
			times,
			time,
			sale_id
		} = data;
		let res = {
			code: 0,
			msg: "",
			data: {}
		};
		// 业务逻辑开始-----------------------------------------------------------
		let nowDate = new Date()
		console.log(nowDate)
		const timeObj = vk.pubfn.getCommonTime(new Date())
		let startTimestamp = 0
		let step = 0
		let steps = []

		switch (type) {
			case 'custom':
				startTimestamp = time[0]
				nowDate = new Date(time[1])
				step = 24 * 60 * 60 * 1000
				break
			case 'year':
				startTimestamp = timeObj.yearStart
				steps = timeObj.months
				break
			case 'month':
				startTimestamp = timeObj.monthStart
				step = 24 * 60 * 60 * 1000
				break
			case 'week':
				startTimestamp = timeObj.weekStart
				step = 24 * 60 * 60 * 1000
				break
		}

		const map = {
			status: 2,
			_add_time: _.gt(startTimestamp)
		}

		const obj = await db.collection('uni-id-base-order').where(map).field().get()
		const orderList = obj.data


		let arr1 = []
		let arr2 = []

		if (type != 'year') {
			for (let i = startTimestamp; i <= nowDate; i += step) {
				let payArr = orderList.filter(item => {
					return item._add_time >= i && item._add_time < i + step
				}).map(item => {
					return item.total_fee
				})
				let money = 0
				if (payArr.length > 0) {
					money = +(payArr.reduce((a, b) => a + b))
				}
				arr1.push({
					_id: vk.pubfn.timeFormat(i, "MM-dd"),
					count: payArr.length || 0
				})
				arr2.push({
					_id: vk.pubfn.timeFormat(i, "MM-dd"),
					count: money
				})
			}
		}
		if (type == 'year') {
			console.log()
			let end = nowDate.getMonth() + 2
			for (let i = 1; i < end; i++) {
				let payArr = orderList.filter(item => {
					return item._add_time >= steps[i].monthStart && item._add_time < steps[i].monthEnd
				}).map(item => {
					return item.total_fee
				})
				
				let money = 0
				if (payArr.length > 0) {
					money = +(payArr.reduce((a, b) => a + b))
				}
				
				arr1.push({
					_id: vk.pubfn.timeFormat(steps[i].monthStart, "yyyy-MM"),
					count: payArr.length || 0
				})
				arr2.push({
					_id: vk.pubfn.timeFormat(steps[i].monthStart, "yyyy-MM"),
					count: money
				})
			}
		}


		res.data.arr1 = arr1
		res.data.arr2 = arr2
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
